package xyz.ranyh.jobclient;

import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import xyz.ranyh.jobclient.http.RegisterTask;

public class SignupActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        final TextView mEmail = (TextView) findViewById(R.id.email);
        final TextView mPassword = (TextView) findViewById(R.id.password);
        final TextView mNickname = (TextView) findViewById(R.id.nickname);

        Button mSignupBtn = (Button) findViewById(R.id.sign_up_btn);
        mSignupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String email = String.valueOf(mEmail.getText());
                final String password =  String.valueOf(mPassword.getText());
                String nickname = String.valueOf(mNickname.getText());
                new RegisterTask(email, password, nickname) {
                    @Override
                    protected void onPostExecute(final JSONObject success) {
                        try {
                            if (success != null && success.getString("error").equals("0")) {

                                Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
                                intent.putExtra("email", email);
                                intent.putExtra("password", password);
                                finish();
                                startActivity(intent);
                            }
                            showToast(success.getString("message"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        Log.d("Message", ob.msg);
                    }

                }.execute();
            }
        });
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
